import sendRequest from "../utils/request.js";
import { Toast } from 'vant';
import responseMap from "./mock";
import {forceLogin, doLogin} from '../utils/requestLogin'
import {getSign} from '../utils/sign'
import {signSeed, ifMock, requireName} from '../utils/config'

const ajax = async (
  apiName,
  params,
  config = {
    requireLogin: false,
    ifSign: false,
    errorHandlar: null,
    urlName: null,
    miniJumpAddress: null
  }
) => {
  const {requireLogin, ifSign, errorHandlar, urlName, miniJumpAddress} = config
  return new Promise(async (resolve, reject) => {
    let extraParams = {}
    if(requireLogin){
      let loginParams = await doLogin(miniJumpAddress)
      Object.assign(extraParams, loginParams);
    }
    if(ifSign){
      const { sign,timeStamp } = await getSign(params, signSeed);
      Object.assign(extraParams,{ sign, timeStamp });
    }
    sendRequest(urlName || requireName, {
      serviceName: apiName,
      data: {
        ...params, 
        ...extraParams
      },
    })
      .then(res => {
        if(res.header.rspCode == 0){
          resolve(res.body);
        }else{
          if(errorHandlar){
            errorHandlar(res)
            return reject(res);
          }
          Toast(res.header.rspDesc || res.header.errMsg || "网络错误，请刷新重试")
          // 授权失败
          if (res.header && res.header.rspCode == -1) {
            return forceLogin(miniJumpAddress)
          }
          reject(res);
        }
      })
      .catch(rej => {
        if(errorHandlar){
          errorHandlar(rej)
          return reject(rej);
        }
        Toast(rej.errMsg || "网络错误，请刷新重试")
        reject(rej);
      });
  });
};

const mockAjax = (apiName, params) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      let result = responseMap[apiName];
      if (Object.prototype.toString.call(result) === "[object Function]") {
        result = result(params);
      }
      resolve({...result});
    }, 200);
  });

export default ifMock ? mockAjax : ajax;

